#include "linuxterminalhelper.h"

#include <QDir>
#include <QProcess>
#include <QStandardPaths>

LinuxTerminalHelper::LinuxTerminalHelper()
{
    terminals = {
//        {"GNOME Terminal", "gnome-terminal", {"--working-directory=%1"}},
//        {"Konsole", "konsole", {"--workdir", "%1"}},
//        {"XFCE Terminal", "xfce4-terminal", {"--working-directory=%1"}},
//        {"Terminator", "terminator", {"--working-directory=%1"}},
//        {"LXTerminal", "lxterminal", {"--working-directory=%1"}},
//        {"Mate Terminal", "mate-terminal", {"--working-directory=%1"}},
//        {"XTerm", "xterm", {"-e", "bash", "-c", "cd \"%1\" && exec bash"}},
//        {"UXTerm", "uxterm", {"-e", "bash", "-c", "cd \"%1\" && exec bash"}},
//        {"Kitty", "kitty", {"--directory=%1"}},
//        {"Alacritty", "alacritty", {"--working-directory", "%1"}},

        {"Deepin Terminal", "deepin-terminal", {"--work-directory", "%1"}},
        {"Gxde Terminal", "gxde-terminal", {"--work-directory", "%1"}},
    };
}

QPair<bool, TerminalInfo> LinuxTerminalHelper::isTerminalSupported()
{
    QPair<bool, TerminalInfo> support;

    LinuxTerminalHelper helper;

    for (const auto& terminal : helper.terminals) {
        if (!QStandardPaths::findExecutable(terminal.command).isEmpty()) {
            support.first = true;
            support.second = terminal;
            break;
        }
    }

    return support;
}

bool LinuxTerminalHelper::openTerminalHere(const QString &directoryPath)
{
    QDir dir(directoryPath);
    if (!dir.exists()) {
        return false;
    }

    LinuxTerminalHelper helper;

    // 遍历查找可用的终端
    for (const auto& terminal : helper.terminals) {
        QString executablePath = QStandardPaths::findExecutable(terminal.command);
        if (!executablePath.isEmpty()) {
            // 构建参数列表，替换占位符
            QStringList arguments;
            for (const QString& arg : terminal.arguments) {
                arguments << arg.arg(directoryPath);
            }

            // 启动终端
            if (QProcess::startDetached(terminal.command, arguments)) {
                return true;
            }
        }
    }

    return false;
}
